// index.js
const app = getApp()
Page({
  data: {
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    documents: []
  },
  onLoad: function () {
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse) {
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
    // 模拟获取文档列表
    this.setData({ 
      documents: [
        { id: 1, title: '文档1' },
        { id: 2, title: '文档2' },
        { id: 3, title: '文档3' },
        { id: 4, title: '文档4' },
        { id: 5, title: '文档5' },
        { id: 6, title: '文档6' },
        { id: 7, title: '文档7' },
        { id: 8, title: '文档8' },
        { id: 9, title: '文档9' },
        { id: 10, title: '文档10' },
        { id: 11, title: '文档11' },
        { id: 12, title: '文档12' },
        { id: 13, title: '文档13' },
        { id: 14, title: '文档14' },
        { id: 15, title: '文档15' }
      ]
    });
  },
  getUserInfo: function(e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  importDocument: function() {
    wx.showToast({
      title: '导入功能待实现',
      icon: 'none'
    })
  },
  createDocument: function() {
    wx.showModal({
      title: '创建文档',
      content: '请输入文档名称',
      editable: true,
      success: (res) => {
        if (res.confirm) {
          const newDoc = {
            id: this.data.documents.length + 1,
            title: res.content
          }
          this.setData({
            documents: [newDoc, ...this.data.documents]
          })
        }
      }
    })
  },
  goToEdit: function(e) {
    const docId = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/edit/edit?id=${docId}`
    })
  }
})
